package com.scriptback.repository;

import com.scriptback.entity.Project;
import com.scriptback.entity.Scripts;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

/**
 * 脚本数据访问接口
 */
@Repository
public interface ScriptRepository extends JpaRepository<Scripts,String> {
    // 分页查询所有脚本
    @Query("SELECT S FROM Scripts S ORDER BY S.id DESC ")
    Page<Scripts> findAllScripts(Pageable pageable);

    // 分页查询指定项目下的脚本
    @Query("SELECT S FROM Scripts S WHERE S.projectId = :projectId ORDER BY S.id DESC")
    Page<Scripts>findAllScriptByProjectId(@Param("projectId") String projectId, Pageable pageable);

    // 分页按脚本名称模糊查询
    @Query("SELECT s FROM Scripts s WHERE UPPER(s.name) LIKE UPPER(CONCAT('%',:name,'%'))")
    Page<Scripts> findSciptsByScriptName(@Param("name") String name, Pageable pageable);

    // 分页在指定项目中按脚本名称模糊查询
    @Query("SELECT S FROM Scripts S WHERE S.projectId = :projectId AND UPPER(S.name)  LIKE UPPER(CONCAT('%',:sciptName,'%'))  ")
    Page<Scripts>findSciptsByProjectIdAndSciptName(Pageable pageable, String projectId, @Param("sciptName")String sciptName);

    // 检查在指定项目中脚本名称是否存在（用于验证重复）
    boolean existsByProjectIdAndName(String projectId, String name);

    // 统计指定项目下的脚本数量
    @Query("SELECT COUNT(s) FROM Scripts s WHERE s.projectId = :projectId")
    long countByProjectId(@Param("projectId") String projectId);

}
